package mx.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import mx.entity.Auth;
import mx.entity.Manage;
import mx.service.AuthService;
import mx.service.ManageService;
import mx.utils.StringUtil;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/manage")
public class ManageController {
	@Resource
	private ManageService manageService;
	@Resource
	private AuthService authService;

	@RequestMapping("/login")
	public ModelAndView login(Manage manage, HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		try {
			if (StringUtil.isEmpty(manage.getUserName()) && StringUtil.isEmpty(manage.getPassword())) {
				mv.setViewName("login");
				return mv;
			} else {
				Subject subject = SecurityUtils.getSubject();
				String userName=manage.getUserName();
				UsernamePasswordToken token = new UsernamePasswordToken(userName, manage.getPassword());
				subject.login(token);// 登陆认证
				manage = manageService.getByUserName(userName);
				Map <String,List<Auth>> map= authService.findById(manage.getRole().getAuthIds());
				System.out.println(map);
				mv.addObject("map", map);
				mv.setViewName("admin/main");
				return mv;
			}
		} catch (Exception e) {
			e.printStackTrace();
			request.setAttribute("manage", manage);
			request.setAttribute("errorInfo", "用户名或密码错误！");
			mv.setViewName("login");
			return mv;
		}
	}
}
